package com.hgm.study.ui.components

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.dp

@Composable
fun ChartView(modifier: Modifier = Modifier, points: List<Double>) {
      //每一行的高度
      val heightRow = 24
      //总行数
      val countRow = 5
      //圆点的半径
      val circleRadius = 2.5
      //24*5/15，每8dp代表一个积分，也就是每行3积分
      val perY = 8
      //画布高度
      val canvasHeight = heightRow * countRow + circleRadius * 2
      //画布宽度=屏幕宽度 - padding * 2
      val canvasWidth = LocalConfiguration.current.screenWidthDp - 16 * 2
      //每个点的坐标
      val avgOfWidth = canvasWidth / 7

      Canvas(
            modifier = modifier
                  .size(width = canvasWidth.dp, height = canvasHeight.dp)
                  .padding(top = 14.dp)
      ) {
            //背景横线
            for (index in 0..countRow) {
                  //计算每一行的y点 = 圆点半径 + 行高 * index
                  val y = (circleRadius + heightRow * index).dp.toPx()
                  drawLine(
                        Color(0xFFDBDBDB),
                        start = Offset(x = 0f, y = y),
                        end = Offset(x = size.width, y = y),//这里的x可以用canvasWidth或者系统获取Canvas的宽度，是一样的
                        strokeWidth = 2.5f
                  )
            }


            //圆圈、折现
            for (index in 0 until points.count()) {
                  //圆点中心的坐标
                  val circleCenter = Offset(
                        x = (avgOfWidth * index + avgOfWidth / 2).dp.toPx(),
                        y = (heightRow * countRow - points[index] * perY + circleRadius).dp.toPx()
                  )
                  drawCircle(
                        Color(0xFF149EE7),
                        radius = circleRadius.dp.toPx(),
                        center = circleCenter,
                        style = Stroke(width = 5f)
                  )


                  if (index < points.count() - 1) {
                        //计算一个点的坐标
                        val nextPointOffset = Offset(
                              x = (avgOfWidth * (index + 1) + avgOfWidth / 2).dp.toPx(),
                              y = (heightRow * countRow - points[(index + 1)] * perY + circleRadius).dp.toPx()
                        )
                        drawLine(
                              color = Color(0xFF149EE7),
                              start = circleCenter,
                              end = nextPointOffset,
                              strokeWidth = 5f
                        )
                  }

            }
      }

}



